package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username,String password,HttpSession session){
        try {
            Employee employee = employeeService.login(username, password);
            // session.setAttribute("USER_IN_SESSION", employee);
            UserContext.setCurrentUser(employee);

            // 如果不是超级管理员
            if (!employee.isAdmin()) {
                // 把当前登录用户的 权限表达式集合 存入session
                List<String> permissionExpressions = permissionService
                        .selectByEmployeeId(employee.getId());
                // session.setAttribute("PERMISSION_IN_SESSION", permissionExpressions);
                UserContext.setPermissionExpression(permissionExpressions);
            }


            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        // 1.清除用户登录成功之后保存的 session 数据
        session.invalidate();
        // 2. 重定向到登录页面
        return "redirect:/login.html";
    }
}
